[LegacyColorValue = true]; 

{ TSM Moving Average profit targets with var size
  Copyright 2011 P J Kaufman. All rights reserved. }

{ period = length of calculaton
  crossoption =0 using trendline, =1 use price crossing trendline
  entrypriceoption = 0 buy/sell on current close
  						 = 1 buy/sell on next open
  						 = 2 buy/sell next close 
  longonly			 true then only long positions
}
  input: period(80), ptper(252), ptfactor(12), sizeper(20);
  vars:	signal(0), trend(0), printPL(true), size(1), investment(25000), 
  			atrange(0), ptrange(0);
  			
	if sizeper <> 0 then atrange = avgtruerange(sizeper);
	if atrange = 0 or sizeper = 0 then 
			size = 1
		else
			size = investment/(atrange*bigpointvalue); 
			
  	trend = average(close,period);
  	if signal <> 1 and trend[1] < trend[2] and trend > trend[1] then begin
  			buy to cover all contracts this bar on close;
  			buy size contracts this bar on close;
  			signal = 1;
  			end;
  	if signal <> -1 and trend[1] > trend[2] and trend < trend[1] then begin
  			sell all contracts this bar on close;
  			sell short size contracts this bar on close;
  			signal = -1;
  		end;
  		
{ profit-taking }
	if ptper <> 0 and ptfactor <> 0 then begin
		ptrange = avgtruerange(ptper);
		if marketposition > 0 then sell ("PT_long") all contracts next bar at entryprice + ptfactor*ptrange limit
			else if marketposition < 0 then buy to cover  ("PT_short") all contracts  
					next bar at entryprice - ptfactor*ptrange limit;
		end;	
  		
  	If printPL then begin
  		If Currentbar = 1 then print(file("c:\TSM5\MA_PT_PL_varsize.csv"), "Date,size,netPL");
  		print(file("c:\TSM5\MA_PT_PL_varsize.csv"),date:8:0, ",", size:8:3, ",", 
  						netprofit + openpositionprofit:5:5);
		end;